package server.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import server.control.Settings;

public class UserInteraction {
	
	private static Logger logger = Logger.getLogger(UserInteraction.class.getName());

	public static boolean registerNewUser(String surname, String firstname, String email, String password){
		
		Connection con = ConnectionPool.getInstance().getConnection();
		PreparedStatement stmt = null;
		String insert;
		
		insert = "INSERT INTO `USER` (`surname`, `firstname`, `email`, `password`, `points`) "
				+ "VALUES ('" + surname + "', '" + firstname + "', '" + email + "', '" + password + "', '0');";
		
		try{
			stmt = con.prepareStatement(insert);
			stmt.executeUpdate();
			return true;
		}catch(SQLException e){
			logger.warn(e);
			return false;
		}finally{
			try{
				if(stmt != null)
					stmt.close();
				if(con != null)
					con.close();
			}catch(SQLException e){
				logger.warn("Couldn't close SQLInteraction. Exception: " + e);
			}
		}
	}

	public static String loginUser(String email, String password){
		
		Connection con = ConnectionPool.getInstance().getConnection();
		PreparedStatement stmt = null;
		ResultSet res = null;
		String query = null;
		
		query = "SELECT uid, email, password FROM USER WHERE email = '" + email + "' AND password = '" + password + "';" ;
		
		try{
			stmt = con.prepareStatement(query);
			res = stmt.executeQuery();
			logger.debug(query);
			if(res.next()){
				return res.getString("uid");
			}else{
				return "-1";
			}
		}catch(SQLException e){
			logger.warn(e);
			return "-1";
		}finally{
			try{
				if(stmt != null)
					stmt.close();
				if(con != null)
					con.close();
			}catch(SQLException e){
				logger.warn("Couldn't close SQLInteraction. Exception: " + e);
			}
		}
	}
	
	static public boolean isRegisteredUser(String email){
		Connection con = ConnectionPool.getInstance().getConnection();
		PreparedStatement stmt = null;
		ResultSet res = null;
		String query = null;
		
		query = "SELECT email FROM USER WHERE email = '" + email + "';" ;
		
		try{
			stmt = con.prepareStatement(query);
			res = stmt.executeQuery();
			if(res.next()){
				return true;
			}else{
				return false;
			}
		}catch(SQLException e){
			logger.warn(e);
			return false;
		}finally{
			try{
				if(stmt != null)
					stmt.close();
				if(con != null)
					con.close();
			}catch(SQLException e){
				logger.warn("Couldn't close SQLInteraction. Exception: " + e);
			}
		}
	}
}
